package com.atos.smp.actions;

import java.io.IOException;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.codeissue.web.common.ServiceFinder;

import com.atos.smp.beans.Collaborator;
import com.atos.smp.beans.Rule;
import com.atos.smp.business.CollaboratorManager;
import com.atos.smp.business.impl.CollaboratorManagerImpl;
import com.atos.smp.dao.CollaboratorDao;

@ManagedBean
@SessionScoped
public class AuthentificationBean {
	
	private CollaboratorManager collaboratorManager;
	private Collaborator collaborator;
	private String das;
	private String password;
	
	public AuthentificationBean() {
		collaboratorManager = Action.getCollaboratorManager();
		HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(true);
		AuthentificationBean aB =(AuthentificationBean) session.getAttribute("authentificationBean");
		if(aB !=null && aB.getCollaborator()!=null)
			collaborator =aB.getCollaborator();

	}
	public Collaborator getCollaborator() {
		
		return collaborator;
	}

	public void setCollaborator(Collaborator collaborator) {
		this.collaborator = collaborator;
	}
	public String getDas() {
		return das;
	}

	public void setDas(String das) {
		this.das = das;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String login(){
		Collaborator c = collaboratorManager.findCollaboratorByDas(getDas());
		if(c!=null && c.getPassword().equals(getPassword())){
			collaborator = c;
			if(c.getRule().equals(Rule.ADMIN))
				
				return "loginAdminSuccess";	
			else
				return "loginManagerSuccess";	

		}
		else {
			return "loginFail";
		}
	}
	
	public String logout() {
		FacesContext context = FacesContext.getCurrentInstance();
		HttpSession session = (HttpSession) context.getExternalContext().getSession(true);
		session.invalidate();
		collaborator = null;
		return "logout";
	}
}
